<?php

namespace App\Http\Controllers\merchant;

use App\Http\Controllers\Controller;
use App\Models\Admin\Config;
use App\Models\Admin\InterfaceConfiguration;
use App\Models\Mysql\XnLogo;
use App\Models\Mysql\XnMechantInfos;
use App\Models\Mysql\XnMerchant;
use App\Models\Mysql\XnMerchantBill;
use App\Models\Mysql\XnOrder;
use App\Models\Mysql\XnOrderBill;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Storage;
use Qiniu\Auth;


class MerchantLogonController extends Controller
{
    //
    /**
     * @param Request $request
     */
    public function __construct( Request $request)
    {
        $this->middleware("auth:merchant", ['except' => ['login', 'refresh','register','no_password']]);
    }

    //登录
    public function login(Request $request)
    {

        // TODO 验证码处理
        $credentials = $request->only(['phone', 'password']);
        $token = auth('merchant')->attempt($credentials);
        if (!$token) {
            return $this->sendError("登录失败");
        }
        return $this->respondWithToken($token, '登录成功');
    }

    //退出
    public function logout()
    {
        auth('merchant')->logout();

        return $this->sendResponse('bye bye', '退出成功');
    }

    //刷新
    public function refresh()
    {
        return $this->respondWithToken(auth('merchant')->refresh(), '刷新成功');
    }

    /**
     * @param string $token
     * @param string $message
     */
    protected function respondWithToken(string $token, string $message)
    {
        return $this->sendResponse([
            'user'=> auth('merchant')->user(),
            'access_token' => $token,
            'token_type' => 'Bearer',
            'expires_in' => auth('merchant')->factory()->getTTL() * 60
        ], $message);
    }

    //商户注册
    public function register(Request $request){
        $params = $request->all();
        if (empty($params['phone'])){
            return $this->sendError('手机号不能为空');
        }
        if (empty($params['password'])){
            return $this->sendError('请设置登录密码');
        }
        if (empty($params['name'])){
            return $this->sendError('请填写真实姓名');
        }
        if (empty($params['nickname'])){
            return $this->sendError('请填写公司名称');
        }
        if (empty($params['transaction_password'])){
            return $this->sendError('请输入六位交易密码');
        }
        if (empty($params['code'])){
            return $this->sendError('请输入手机验证码');
        }
//        Redis::get();
        $info =[
            'name'=>$params['name'],
            'nickname'=>$params['nickname'],
            'phone'=>$params['phone'],
            'password'=>password_hash($params['password'], PASSWORD_DEFAULT),
            'merchant_number'=>'1'.substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8),
            'transaction_password'=>md5($params['transaction_password']),
            'secret_key'=>password_hash(md5($params['phone']), PASSWORD_DEFAULT),
            'time'=>date('Y-m-d H:i:s')
        ];
        $phone = XnMerchant::where('phone',$params['phone'])->first();
        if (!empty($phone)){
            return $this->sendError('手机号已经被注册');
        }
        $res = XnMerchant::insert($info);
        if (!$res) {
            return $this->sendError('注册失败');
        }
        return $this->sendResponse($res,'注册成功');
   }
    //商户忘记密码
    public function no_password(Request $request){
        $params = $request->all();

        if (empty($params['phone'])){
            return $this->sendError('请输入手机号');
        }
        if (empty($params['code'])){
            return $this->sendError('请输入验证码');
        }
        if (!$this->is_phone($params['phone'])){
            return $this->sendError('请输入正确的手机号码');
        }
//        $phone          = $params['phone'];
//        $code           = $params['code'];
//
//        $value = Redis::get('merchant_logon'.$phone);
//        if (empty($value)) {
//            return $this->sendError('验证码已失效');
//        }
//        if ($value != $code) {
//            return $this->sendError('验证码错误');
//        }
//        Redis::del('merchant_logon'.$phone);
        $res = XnMerchant::where('phone',$params['phone'])->update(['password'=>password_hash($params['transaction_password'], PASSWORD_DEFAULT)]);
        if (!$res){
            return $this->sendError('重置失败');
        }
        return $this->sendResponse([],'重置密码成功');
    }
    //商户实名认证
    public function authentication(Request $request){
        $params = $request->all();
        if (empty($params['type'])){
            return $this->sendError('类型不能为空');
        }
        $user = auth('merchant')->user();
        $info = [];
        $type = $params['type'];

        if ($type == 1){ //企业用户
            $info = [
                'merchant_id'=>$user->id,
                'merchant_number'=>$user->merchant_number,
                'LicenseImg'=>$params['LicenseImg'],
                'Credit_Identifier'=>$params['Credit_Identifier'],
                'Legal_person'=>$params['Legal_person'],
                'enterprise_name'=>$params['enterprise_name'],
                'reply_time'=>date('Y-m-d H:i:s'),
            ];
        }
        if ($type == 2){ //个人用户
            $info = [
                'merchant_id'=>$user->id,
                'merchant_number'=>$user->merchant_number,
                'Legal_person'=>$params['Legal_person'],
                'Id_frontImg'=>$params['id_card_front_photo'],
                'Id_oppositeImg'=>$params['id_card_reverse_photo'],
                'u_id'=>$params['u_id'],
                'reply_time'=>date('Y-m-d H:i:s'),
            ];
        }

        DB::beginTransaction();
        if (!XnMechantInfos::where('merchant_id',$user->id)->first()){
            XnMechantInfos::insert($info);
        }else{
            XnMechantInfos::where('merchant_id',$info['merchant_id'])->update($info);
        }
        XnMerchant::where('id',$user->id)->update(['user_type'=>$type,'status'=>5]);
        Db::commit();
        return $this->sendResponse([],'提交成功');
        Db::rollBack();
        return $this->sendError('提交失败');
    }
    //商户实名认证页信息
    public function authentication_info(){
        $user = auth('merchant')->user();
        $res = XnMechantInfos::where('merchant_number',$user->merchant_number)->first();
        $res['user_type'] = $user['user_type'];
        $res['status'] = $user['status'];
        if (!$res){
            return $this->sendError('查询失败');
        }
        return $this->sendResponse($res,'查询成功');
    }

    //上传图片
    public function uploadpic(Request $request)
    {
        $file=$request->file('file');
        if(empty($file)){
           return $this->sendError('请上传图片');
        }
        $fileextension=$file->getClientOriginalExtension();
        $filesize=$file->getSize()/1000;
        if($filesize >=2000){
            return $this->sendError('文件太大');
        }
        $realpath=$file->getRealPath();
        $storage_path = public_path('uploads/merchant');
        $filenewname=date('YmdHis').rand(000,999).'.'.$fileextension;
        if($file->isValid())
        {
            Storage::disk('public')->put($filenewname, file_get_contents($realpath));
            $file->move($storage_path,$filenewname);
            $path = '/uploads/merchant/'.$filenewname;
            return $this->sendResponse($request->schemeAndHttpHost().$path,'上传成功');
        }else{
            return $this->sendError('图片不合法');
        }
    }


}
